<!-- 用户管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 部门树 -->
      <!-- <el-col :lg="4" :xs="24" class="mb-[12px]">
        <DeptTree v-model="queryParams.deptId" @node-click="handleQuery" />
      </el-col> -->

      <!-- 用户列表 -->
      <el-col :xs="24">
        <div class="search-bar">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="用户名称" prop="userName">
              <el-input
                v-noSpace
                v-model="queryParams.name"
                placeholder="请输入用户名称"
                clearable
                @keyup.enter="handleQuery"
                class="!w-[192px]"
              />
            </el-form-item>

            <el-form-item label="登录账号" prop="loginAccount">
              <el-input
                v-noSpace
                v-model="queryParams.account"
                placeholder="请输入登录账号"
                clearable
                @keyup.enter="handleQuery"
                class="!w-[192px]"
              />
            </el-form-item>

            <el-form-item label="角色名称">
              <el-select
                v-model="queryParams.sysUserRoles"
                multiple
                placeholder="请选择角色"
                class="!w-[192px]"
                clearable
                @change="handleQuery"
              >
                <el-option
                  v-for="role in roleOptions"
                  :id="role.id"
                  :key="role.roleId"
                  :label="role.label"
                  :value="role.roleId"
                />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button v-hasPerm="'sys:user:edit'" type="warning" @click="handleAddQuery">
                新增
              </el-button>
              <!-- <el-button @click="handleDelete()">删除</el-button> -->
              <el-button @click="handleResetQuery()">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
          <el-table v-loading="loading" :data="pageData" @selection-change="handleSelectionChange">
            <!-- <el-table-column type="selection" align="center" /> -->

            <el-table-column label="序号" align="center">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="用户名称" align="center" prop="name" />
            <el-table-column label="登录账号" align="center" prop="account" />
            <el-table-column label="用户类型" align="center" prop="category">
              <template #default="scope">
                <el-tag v-if="scope.row.category === 0">系统用户</el-tag>
                <el-tag v-if="scope.row.category === 1">商城用户</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="角色" align="center" prop="sysUserRoles" width="150">
              <template #default="scope">
                <div class="gap-2">
                  <el-tag
                    v-for="item in scope.row.sysUserRoles.slice(0, 1)"
                    :key="item.moduleId"
                    size="small"
                  >
                    {{ item.roleName }}
                  </el-tag>
                  <el-tooltip
                    v-if="scope.row.sysUserRoles.length > 1"
                    effect="dark"
                    placement="top"
                  >
                    <el-tag type="info">+{{ scope.row.sysUserRoles.length - 1 }} 更多</el-tag>
                    <template #content>
                      {{ scope.row.sysUserRoles.map((item: any) => item.roleName).join(",") }}
                    </template>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="职位" align="center" prop="jobTitle" />
            <el-table-column label="邮箱" align="center" prop="mail" />

            <el-table-column label="电话" align="center" prop="phone" />

            <el-table-column label="创建时间" align="center" prop="createTime" />
            <el-table-column label="操作" width="180" align="center" fixed="right">
              <template #default="scope">
                <el-tag v-if="scope.row.userName === 'admin'" type="info">不可操作</el-tag>
                <div v-else>
                  <el-button
                    v-hasPerm="'sys:user:edit'"
                    type="primary"
                    link
                    size="small"
                    v-if="scope.row.id !== 1"
                    @click="handleOpenDialog(scope.row.id, scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    v-hasPerm="'sys:user:del'"
                    type="danger"
                    link
                    size="small"
                    v-if="scope.row.id !== 1 || scope.row.allowDel == 1"
                    @click="handleDelete(scope.row.id)"
                  >
                    删除
                  </el-button>
                  <el-button
                    v-hasPerm="'sys:user:password:edit'"
                    type="danger"
                    link
                    size="small"
                    v-if="scope.row.id !== 1"
                    @click="handleResetPwd(scope.row.id)"
                  >
                    修改密码
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户表单 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      align-center
      width="420px"
      :close-on-click-modal="false"
      :class="['custom-dialog']"
      @close="handleCloseDialog"
    >
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="100px">
        <div v-if="!updatePwdVisible">
          <el-form-item label="用户类型" prop="category">
            <el-select
              v-model="formData.category"
              placeholder="请输入用户类型"
              style="width: 250px"
              maxlength="15"
              :disabled="!!formData.id"
              @change="handleCategoryChange"
            >
              <el-option
                v-for="item in userTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户名称" prop="name">
            <el-input
              v-noSpace
              v-model="formData.name"
              placeholder="请输入用户名称"
              style="width: 250px"
              maxlength="15"
            />
          </el-form-item>

          <el-form-item label="登录账号" prop="account">
            <el-input
              v-noSpace
              v-model="formData.account"
              placeholder="请输入登录账号"
              autocomplete="false"
              style="width: 250px"
              maxlength="20"
            />
          </el-form-item>
          <el-form-item v-if="dialog.isAdd" label="密码" prop="password">
            <el-input
              v-noSpace
              v-model="formData.password"
              placeholder="请输入密码"
              autocomplete="false"
              style="width: 250px"
              type="password"
              maxlength="20"
              show-password
            />
          </el-form-item>

          <el-form-item label="用户角色" prop="sysUserRoles">
            <el-select
              v-model="formData.sysUserRoles"
              multiple
              placeholder="请选择角色"
              style="width: 250px"
              @change="handleChangeSelect"
            >
              <el-option
                v-for="item in roleOptions"
                :key="item.roleId"
                :label="item.label"
                :value="item.roleId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="职位" prop="jobTitle">
            <el-input
              v-noSpace
              v-model="formData.jobTitle"
              placeholder="请输入职位"
              style="width: 250px"
            />
          </el-form-item>

          <el-form-item label="邮箱" prop="mail">
            <el-input
              v-noSpace
              v-model="formData.mail"
              placeholder="请输入邮箱"
              maxlength="50"
              type="email"
              style="width: 250px"
            />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input
              v-noSpace
              v-model="formData.phone"
              placeholder="请输入电话"
              maxlength="11"
              style="width: 250px"
            />
          </el-form-item>
          <el-form-item label="是否关联用户" prop="linkUser">
            <el-switch v-model="formData.linkUser" @change="handleLinkChange" />
          </el-form-item>
          <el-form-item
            v-if="formData.linkUser && formData.category === 0"
            label="钉钉账号"
            prop="employeeId"
          >
            <!-- <el-select-v2
              v-model="formData.employeeId"
              :options="dingTalkOptions"
              filterable
              remote
              :remote-method="remoteMethod"
              :loading="loading"
              @visible-change="getDingTalkList"
            /> -->

            <el-select
              prop="employeeId"
              v-model="formData.employeeId"
              placeholder="请输入钉钉账号"
              style="width: 250px"
              filterable
              remote
              :remote-method="getDingTalkList"
              :loading="loading"
            >
              <el-option
                v-for="item in dingTalkOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <!-- 商城用户关联客户 -->
          <el-form-item
            v-if="formData.linkUser && formData.category === 1"
            label="客户账号"
            prop="companyCode"
          >
            <el-select
              v-model="formData.companyCode"
              placeholder="请输入客户账号"
              style="width: 250px"
              filterable
              remote
              :remote-method="getCompanyList"
              :loading="loading"
            >
              <el-option
                v-for="item in customerOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value.toString()"
              />
            </el-select>
          </el-form-item>
        </div>
        <div v-else>
          <!-- 修改密码 -->
          <el-form-item label="登录账号" prop="account">
            <el-input
              v-noSpace
              v-model="formData.account"
              placeholder="请输入登录账号"
              style="width: 250px"
              autocomplete="false"
            />
          </el-form-item>
          <el-form-item label="新密码" prop="password">
            <el-input
              v-noSpace
              v-model="formData.password"
              placeholder="请输入新密码"
              autocomplete="false"
              style="width: 250px"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-noSpace
              v-model="confirmPassword"
              autocomplete="false"
              placeholder="请输入新密码"
              style="width: 250px"
              type="password"
              show-password
            />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-debounce="handleSubmit" type="primary">保存</el-button>
          <el-button @click="handleCloseDialog">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import UserAPI, { UserForm, UserPageQuery, UserPageVO, Role } from "@/api/system/user";

import RoleAPI from "@/api/system/role";
import organizationalAPI, { Department } from "@/api/basicData/organizational";
import cusInfoApi from "@/api/cusManage/cusInfo";

defineOptions({
  name: "User",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const userFormRef = ref(ElForm);

let queryParams = reactive<UserPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const pageData = ref<UserPageVO[]>();

let baseDataList: any[] | undefined;

const total = ref(0);
const loading = ref(false);

const dialog = reactive({
  visible: false,
  title: "新增用户",
  isAdd: true,
});
//修改密码
// 是否显示修改密码
let updatePwdVisible = ref(false);
// 确认密码
const confirmPassword = ref("");

const handleCategoryChange = (val: any) => {};

const handleResetPwd = (id: number) => {
  //console.log(id, "id");

  updatePwdVisible.value = true;
  handleOpenDialog(id);
};

let formData = reactive<UserForm & { linkUser: boolean }>({
  category: 0,
  linkUser: false,
});

//用户类型
const userTypeOptions = [
  { label: "系统用户", value: 0 },
  { label: "商城用户", value: 1 },
];

//是否关联用户
const handleLinkChange = (val: boolean | string | number) => {
  console.log(val, "handleLinkChange");

  // if (!val) {
  //   formData.employeeId = NaN;
  //   formData.companyCode = "";
  // }
};

//客户下拉列表
const customerOptions = ref<
  {
    label: string;
    value: string;
  }[]
>([]);

//获取客户列表
const getCompanyList = (query: string) => {
  if (query) {
    loading.value = true;
    cusInfoApi.getPage({ pageNum: 1, pageSize: 999, companyName: query }).then((res) => {
      customerOptions.value = res.records.map((item: any) => {
        return {
          label: item.companyName,
          value: item.code,
        };
      });
      loading.value = false;
    });
  } else {
    loading.value = true;
    cusInfoApi.getPage({ pageNum: 1, pageSize: 999, companyName: query }).then((res) => {
      customerOptions.value = res.records.map((item: any) => {
        return {
          label: item.companyName,
          value: item.code,
        };
      });
      loading.value = false;
    });
  }
};

//钉钉下拉列表
const dingTalkOptions = ref<
  {
    label: string;
    value: number;
  }[]
>([]);

//获取钉钉列表
const getDingTalkList = (query: string) => {
  if (query) {
    loading.value = true;
    organizationalAPI
      .getEmployeeList({ pageNum: 1, pageSize: 999, employeeName: query })
      .then((res) => {
        dingTalkOptions.value = res.list.map((item) => {
          return {
            label: item.employeeName,
            value: item.id,
          };
        });
        loading.value = false;
      });
  } else {
    organizationalAPI.getEmployeeList({ pageNum: 1, pageSize: 999 }).then((res) => {
      dingTalkOptions.value = res.list.map((item) => {
        return {
          label: item.employeeName,
          value: item.id,
        };
      });
    });
  }
};

//修改密码校验

const pwdValidator = (rule: any, value: string, callback: any) => {
  if (confirmPassword.value === "") {
    callback(new Error("请再次输入密码"));
  } else if (confirmPassword.value !== formData.password) {
    callback(new Error("两次密码不一致，请检查密码"));
  } else {
    //console.log("修改密码校验成功");

    callback();
  }
};

const rules = reactive({
  name: [
    { required: true, message: "用户名称不能为空", trigger: "blur" },

    { max: 15, message: "用户名称不能超过15个字", trigger: "blur" },
  ],
  account: [
    { required: true, message: "登录账号不能为空", trigger: "blur" },
    //最多20个字符，只能包含数字和字母，不能以数字开头
    { max: 20, message: "登录账号不能超过20个字符", trigger: "blur" },
    { pattern: /^[a-zA-Z][a-zA-Z0-9]*$/, message: "登录账号不能以数字开头", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度为6-20位", trigger: "blur" },
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d).{6,20}$/,

      message: "密码必须同时包含数字和字母",
      trigger: "blur",
    },
  ],
  confirmPassword: [{ required: true, validator: pwdValidator, trigger: "blur" }],

  sysUserRoles: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],

  mail: [
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  phone: [
    { required: true, message: "电话不能为空", trigger: "blur" },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的电话",
      trigger: "blur",
    },
  ],
});

// 选中的用户ID
const selectIds = ref<number[]>([]);
// 部门下拉数据源
const deptOptions = ref<OptionType[]>();
// 角色下拉数据源
const roleOptions = ref<Role[]>([]);
//下拉框的值
let filteredOptions = ref<Role[]>([]);
let rowData = ref<{ id?: number | undefined }[]>([]);

//获取所有角色
const getSysRoleList = () => {
  RoleAPI.getSysRoleList().then((data) => {
    roleOptions.value = data.list.map((item: any) => {
      return { label: item.roleName, roleId: item.id, id: "" };
    });
    console.log(data.list, "角色列表", roleOptions.value);
  });
};

// 查询
async function handleQuery() {
  //console.log((await RoleAPI.getSysRoleList()).list);

  //处理后的queryParams
  let afterQueryParams: any = {
    ...queryParams,
    sysUserRoles: queryParams.sysUserRoles?.map((item) => ({
      roleId: item,
    })),
  };
  //console.log(afterQueryParams, "角色列表");

  loading.value = true;
  UserAPI.getPage(afterQueryParams)
    .then((data) => {
      pageData.value = data?.list;
      total.value = data?.total || 0;
    })
    .finally(() => {
      loading.value = false;
    });
}
//新增用户
function handleAddQuery() {
  handleOpenDialog();
}
// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
  queryParams.name = "";
  queryParams.sysUserRoles = [];
  queryParams.account = "";
  handleQuery();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
  //console.log(selection, "选中项");
}

/**
 * 打开弹窗
 *
 * @param id 用户序号
 */
async function handleOpenDialog(id?: number, row?: any) {
  dialog.visible = true;
  rowData.value = row?.sysUserRoles;
  console.log(rowData.value, "行数据");

  baseDataList = [];

  if (id) {
    if (updatePwdVisible.value) {
      dialog.title = "修改密码";
    } else {
      dialog.title = "修改用户";
    }
    dialog.isAdd = false;

    UserAPI.getFormData(id)
      .then((data) => {
        formData.id = data?.id;
        formData.name = data?.name;
        formData.account = data?.account;
        baseDataList = data?.sysUserRoles;
        let activeList = baseDataList?.map((item: any) => item.roleId); // 滤出 roleId 存在的项
        if (activeList) {
          formData.sysUserRoles = activeList.slice(); // 可以安全地调用 slice()，因为已经检查了 activeList 的存在性
        } else {
          formData.sysUserRoles = []; // 如果 activeList 是 undefined，则设置一个空数组
          // 或者，您可能想要处理 activeList 为 undefined 的情况，例如显示一个错误消息或执行其他逻辑
        }

        baseDataList?.forEach((baseData: any) => {
          const roleOption = roleOptions.value?.find(
            (option: any) => option.roleId === baseData.roleId
          );
          if (roleOption) {
            roleOption.id = baseData.id;
          }
        });
        formData.category = data?.category;

        formData.jobTitle = data?.jobTitle;
        formData.mail = data?.mail;
        formData.phone = data?.phone;
        formData.employeeId = data?.employeeId;
        formData.companyCode = data?.companyCode;
        formData.linkUser = data?.employeeId || data?.companyCode ? true : false;
      })
      .catch((err) => {
        //console.log(err);

        // ElMessage.error(`${err}`);
        // handleCloseDialog();
        handleResetQuery();
      });
  } else {
    dialog.title = "新增用户";
    dialog.isAdd = true;
  }
}

// 关闭弹窗
function handleCloseDialog() {
  //console.log("关闭");
  //初始化
  dialog.visible = false;
  updatePwdVisible.value = false;
  userFormRef.value?.resetFields();
  userFormRef.value?.clearValidate();
  formData.id = NaN;
  formData.name = "";
  formData.account = "";
  formData.sysUserRoles = [];
  formData.jobTitle = "";
  formData.mail = "";
  formData.phone = "";
  formData.password = "";
  formData.employeeId = NaN;
  formData.companyCode = "";
  formData.linkUser = false;
  confirmPassword.value = "";
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  let queryParams: any;
  //修改密码
  if (updatePwdVisible.value) {
    queryParams = { id: formData.id, password: formData.password };
  } else {
    //修改用户
    // if (rowData.value && rowData.value.length === 1) {
    //   console.log(rowData.value[0], "行数据");

    const sysUserRoles = roleOptions.value?.filter((option: Role) =>
      formData.sysUserRoles?.includes(option.roleId)
    );
    //   filteredOptions.value[filteredOptions.value.length - 1].id = rowData.value[0].id;
    // }
    console.log(baseDataList, "  baseDataList", filteredOptions.value, "过滤后的数据");
    queryParams = { ...formData, sysUserRoles: JSON.parse(JSON.stringify(sysUserRoles)) };
  }
  if (!updatePwdVisible.value && !dialog.isAdd) {
    //删除password
    delete queryParams.password;
  }
  if (formData.linkUser) {
    if (formData.category == 0) {
      queryParams.employeeId = formData.employeeId;
      queryParams.companyCode = "";
    } else {
      queryParams.employeeId = NaN;
      queryParams.companyCode = formData.companyCode;
    }
  } else {
    queryParams.employeeId = NaN;
    queryParams.companyCode = "";
  }

  //console.log(queryParams, "处理后的数据");

  userFormRef.value.validate((valid: boolean) => {
    if (!valid) {
    } else {
      //是否修改
      if (formData.id) {
        console.log(queryParams, "处理后的数据");
        UserAPI.update(queryParams as any)
          .then((data) => {
            ElMessage.success("操作成功");
            //console.log(data, "修改");
            handleQuery();
            handleCloseDialog();
          })
          .catch((err) => {
            //console.log(err);
            // ElMessage.error(`${err}`);
            // handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        UserAPI.add(queryParams as any)
          .then((data) => {
            ElMessage.success("操作成功");
            handleQuery();
            handleCloseDialog();
          })
          .catch((err) => {
            //console.log(err);
            // ElMessage.error(`${err}`);
            // handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 200);

/**
 * 删除用户
 *
 * @param id  用户ID
 */
function handleDelete(id?: number) {
  const userIds = [id || selectIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      UserAPI.deleteByIds(userIds)
        .then((data) => {
          ElMessage.success("删除成功");

          handleQuery();
        })
        .catch((err) => {
          //console.log(err);
          // ElMessage.error(`${err}`);
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

function handleChangeSelect() {
  const actId = formData.sysUserRoles;
  if (!Array.isArray(actId)) {
    console.error("sysUserRoles 不是一个数组");
    return;
  }

  filteredOptions.value = roleOptions.value.filter((option: Role) => actId.includes(option.roleId)); // 过滤出已勾选的项

  //console.log(filteredOptions.value, "filteredOptions");
}
onMounted(() => {
  handleQuery();
  getSysRoleList();
  getDingTalkList("");
  getCompanyList("");
});
</script>
<style scoped>
.custom-dialog .el-dialog__header {
  text-align: center;

  /* 将标题居中 */
}

.custom-dialog .el-dialog__title {
  margin: 0;

  /* 移除默认的左边距，确保标题真正居中 */
}
</style>
